package com.hyc.ssoclienttm.interceptor;

import com.hyc.ssoclienttm.utils.HttpUitl;
import com.hyc.ssoclienttm.utils.SSOClientUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @projectName: SSO_self
 * @package: com.hyc.ssoclienttb.interceptor
 * @className: ssoInterceptor
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/1/9 20:20
 * @version: 1.0
 */
public class ssoInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String httpuri = SSOClientUtil.SERVER_URL_PREFIX + "/islogin";
        HashMap<String, String> isloginparms = new HashMap<>();
        String islogin = HttpUitl.sendHttpRequest(httpuri, isloginparms);
        if (islogin.equals("true")) {
            return true;
        }
        //判断地址栏是否有携带token参数
        String token = request.getParameter("token");
        System.out.println(token);
        if (!StringUtils.isEmpty(token)) {
            System.out.println("检测到token信息，需要去sso服务器验证！");
            //    token 信息不为空 说明拥有令牌，我们需要去认证中心检查这个令牌，以防伪造
            String httpURL = SSOClientUtil.SERVER_URL_PREFIX + "/verify";
            HashMap<String, String> parms = new HashMap<>();
            //放入登出的位置和token
            parms.put("token", token);
            try {
                String isverify = HttpUitl.sendHttpRequest(httpURL, parms);
                if ("true".equals(isverify)) {
                    //    如果返回的字符串是true 说明这个token是由统一认证中心产生的
                    System.out.println("检测到token信息，验证通过");
                    return true;
                } else {
                    SSOClientUtil.redirectToSSOURL(request, response);
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //不存在用通过我们的认证工具类 转发到对应的认证界面 ssoclientuitl
        SSOClientUtil.redirectToSSOURL(request, response);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
